package com.minsheng.epidemic_rep.config;

import com.minsheng.epidemic_rep.entity.DatabaseType;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Aspect
@Component
@Order(1)
public class DataSourceApect {

    private static final Logger log = LoggerFactory.getLogger(DataSourceApect.class);

    @Before("execution(* com.minsheng.epidemic_rep.dao..*.*(..))")
    public void setDataSourceKey(JoinPoint point) {
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();
        MyDataSource ds = method.getDeclaredAnnotation(MyDataSource.class);
        if (null == ds) {
            if (log.isDebugEnabled()) {
                log.debug("如获取不到MyDataSource类注解，则从目标类获取。");
            }
            try {
                Class<?> targetClass = point.getTarget().getClass();
                Method targetMethod = targetClass.getDeclaredMethod(method.getName(), method.getParameterTypes());
                if (null != targetMethod) {
                    ds = targetMethod.getDeclaredAnnotation(MyDataSource.class);
                }
            } catch (Exception e) {
                log.debug("获取目标类注解失败。", e);
            }
        }
        if (null != ds && DatabaseType.MASTER.equals(ds.type())) {
            log.debug("MASTERDB");
            DatabaseContextHolder.setDatabaseType(DatabaseType.MASTER);
        } else if(null != ds && DatabaseType.SLAVE1.equals(ds.type())){
            log.debug("使用SLAVE1DB");
            DatabaseContextHolder.setDatabaseType(DatabaseType.SLAVE1);
        } else {
            log.debug("使用SLAVE2DB");
            DatabaseContextHolder.setDatabaseType(DatabaseType.SLAVE2);
        }
    }

    @After("execution(* com.minsheng.epidemic_rep.dao..*.*(..))")
    public void after(JoinPoint point) {
        DatabaseContextHolder.clearDatabaseType();
    }

}